# -*- coding: utf-8 -*-
"""drawplant.pyw 使用L系统模拟的分形植物
"""
import turtle as tt


def generate(n, result="[X]"):
    """传入迭代次数和生成式返回结果序列
    """
    rules = {"X": "F-[[X]+X]+F[+FX]-X",
             "F": "FF"}
    for _ in range(n):
        for k, v in rules.items():
            result = result.replace(k, v)
    return result


def draw(cmds, size=2):
    """传入结果序列和线段长度绘制图形
    """
    stack = []
    for cmd in cmds:
        if cmd == "F":
            tt.forward(size)
        elif cmd == "-":
            tt.left(25)
        elif cmd == "+":
            tt.right(25)
        elif cmd == "X":
            pass
        elif cmd == "[":
            stack.append((tt.position(), tt.heading()))
        elif cmd == "]":
            position, heading = stack.pop()
            tt.penup()
            tt.setposition(position)
            tt.setheading(heading)
            tt.pendown()
        else:
            raise ValueError("Unknown Cmd: {}".format(ord(cmd)))
    tt.update()


def main():
    """绘图程序主函数
    """
    tt.TurtleScreen._RUNNING = True
    tt.hideturtle()
    tt.tracer(0)
    tt.color("green")
    tt.speed(0)
    tt.left(60)
    tt.pensize(2)
    tt.penup()
    tt.goto(-tt.window_width()/3, -tt.window_height()/3)
    tt.pendown()
    plant = generate(6)
    draw(plant)
    tt.exitonclick()


if __name__ == "__main__":
    main()
